package com.jihox.abookpro;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.igexin.sdk.PushManager;
import com.jihox.abookpro.R.drawable;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.MyTextWatcher;
import com.jihox.abookpro.view.JHProgressDialog;



/**
 * Created by york.gui on 15-6-17.
 * 接收传递过来的手机号，向服务器请求验证码
 * 输入验证码并设置密码，验证后完成注册的活动
 */
public class VerifyPassWordActivity extends BaseActivity {
	
	private static final int REQUEST_TIMEOUT = 100*1000;//设置请求超时100秒钟  
	private static final int SO_TIMEOUT = 100*1000;  //设置等待数据超时时间100秒钟
//	private static final String SHAREDPREFERENCES_CUSTOMERINFO = "CUSTOMER_TOKEN";
			
    private TextView showPhoneNumber;
    private EditText authCode;
    private Button resetAuthCode;
    private Button countDown;
    private EditText customerPassword;
    private Button resetPassword;
    private Button submitButton;
    private Button passwordVisible;
    
    private JHProgressDialog pd;    
    
    private String customerPhoneNumber;
    private String dynamicCode;
    private String cstPassword;
    private String clientId;
    private String fromFlag;//标识从何处跳转来的
    
    private boolean passwordIsHidden = true;//密码不可见

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_signup);        
        initView();       
        //submitButton.setClickable(false);
        Intent intent = getIntent();
        customerPhoneNumber = intent.getStringExtra("signUpPhoneNumber");
        //根据标识位去设置页面信息
        fromFlag = intent.getStringExtra("From");
        if (fromFlag.equals("SignUp")) {
        	customerPassword.setHint(getResources().getString(R.string.X_Set_Password));
        	submitButton.setText(R.string.X_Completed_SignUp);
		}else if(fromFlag.equals("ForgotPassWord")){
			customerPassword.setHint(getResources().getString(R.string.X_Set_New_Password));
			submitButton.setText(R.string.X_Completed_Reset_Password);
		}
        initHeader();        

        //提示信息
        showPhoneNumber.setText(getResources().getString(R.string.Remind_AuthCode_Has_Send) 
        		+ customerPhoneNumber);
        //获取验证码
        getRegisterDynamicCode();    
        

        //新建一个计时器，倒计时60秒，间隔1秒
        TimeCount time = new TimeCount(60000, 1000);
        //倒计时开始
        time.start();
        
        //是否显示清空按钮
        authCode.addTextChangedListener(new MyTextWatcher(resetAuthCode));
        customerPassword.addTextChangedListener(new MyTextWatcher(resetPassword));
        
        //清空验证码
        resetAuthCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                authCode.setText(null);
            }
        });
        //清空设置的密码
        resetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customerPassword.setText(null);
            }
        });

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //取得用户输入的密码和动态验证码
            	cstPassword = customerPassword.getText().toString().trim();
            	dynamicCode = authCode.getText().toString().trim();   
            	if (cstPassword.isEmpty() || dynamicCode.isEmpty()) {
					showToast(getResources().getString(R.string.T_No_DynamicCode_Or_Password));
					return;
				}
            	completedVerify();		
            }

        });
        
        passwordVisible.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if (passwordIsHidden) {
					customerPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
					passwordVisible.setBackgroundResource(drawable.visible_filled_off);
				}else {
	                customerPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
	                passwordVisible.setBackgroundResource(drawable.visible_filled_on);
	            }
	                passwordIsHidden = !passwordIsHidden;				
			}
		});

    
        countDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            	getRegisterDynamicCode();
                TimeCount time = new TimeCount(60000, 1000);//新建一个计时器，倒计时60秒，间隔1秒
                time.start();//倒计时开始                
            }
        });
    }
    /**
     * 获取验证码部分
     */
    //向服务器请求获取验证码
    private void getRegisterDynamicCode(){
		new Thread(getRegisterDynamicCodeRunnable).start();
	}
    
    //提交请求的进程
	private Runnable getRegisterDynamicCodeRunnable = new Runnable() {
			@Override
			public void run() {
				BasicHttpParams httpParams = new BasicHttpParams();  
				//设置连接超时时间
				HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
				HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
				HttpClient httpClient = new DefaultHttpClient(httpParams);
				/**根据fromFlag取得登录地址
				 * SignUp----获取注册动态码
				 * ForgotPassWord----获取重置密码验证码
				 */
				String urlString;
				if (fromFlag.equals("SignUp")) {
					urlString = ConfigProperties.getRegisterDynamicCodeUrl();					
				}else{
					urlString =ConfigProperties.getDynamicCodeForResetPasswordUrl();
				}
				HttpPost httpPost = new HttpPost(urlString);
				Message msg = new Message();
				Bundle data = new Bundle();
				try {
					List<NameValuePair> paramsList = new ArrayList<NameValuePair>();					
					paramsList.add(new BasicNameValuePair("phoneNo", customerPhoneNumber));	
					UserHelper helper = new UserHelper();
					paramsList.add(new BasicNameValuePair("username", helper.getUserName()));
					paramsList.add(new BasicNameValuePair("password", helper.getPassword()));
					UrlEncodedFormEntity entity;							
					entity = new UrlEncodedFormEntity(paramsList, "utf-8");			
					httpPost.setEntity(entity);					
					HttpResponse httpResponse = httpClient.execute(httpPost);//执行请求
					//判断Http响应状态码
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						//获取响应实体
						HttpEntity httpEntity = httpResponse.getEntity();					
						//获取服务器返回的信息，转换为UTF-8编码的字符串
						if (httpEntity != null) {
							String res = EntityUtils.toString(httpEntity, Charset
									.forName("UTF-8").toString());
							Log.i("msg_res", res);
							data.putString("value", res);
							httpEntity.consumeContent();
						}
					}
				} catch (UnsupportedEncodingException e) {
					data.putString("Error", getResources().getString(R.string.T_Link_Error));
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					data.putString("Error", getResources().getString(R.string.T_Link_Error));
						e.printStackTrace();
				} catch (IOException e) {
					data.putString("Error", getResources().getString(R.string.T_Link_Error));
						e.printStackTrace();			
				}finally {
					//发送message。关闭连接
					msg.setData(data);
					getRegisterDynamicCodehandler.sendMessage(msg);
					httpClient.getConnectionManager().shutdown();
				} 
				
			}
		};
		
	private Handler getRegisterDynamicCodehandler = new Handler() {
			
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);		
				Bundle data = msg.getData();
				String error = data.getString("Error");
				if (error != null && !error.isEmpty()) {
					showToast(error);
					return;
				}
				//取出并处理JSON字符串
				String val = data.getString("value");
				try {
					JSONObject result = new JSONObject(val);
					//登录响应状态
					boolean isSuccess = result.getBoolean("success");
					//手机号已经注册过,跳回注册页面，重新回去手机号
					if (!isSuccess) {	
						if(!result.isNull("msg")){
							String message = result.getString("msg");
							showToast(message);
	//						Intent intent = new Intent(VerifyPassWordActivity.this, SignUpActivity.class);
	//						startActivity(intent);
							finish();
						}else{
							showToast("验证码获取失败");
						}
					}
				} catch(Exception e){					
					showToast(getResources().getString(R.string.T_Link_Error));
				}
			}
		};
    
    protected void completedVerify() {
        //提示正在完成验证
        pd = JHProgressDialog.show(VerifyPassWordActivity.this, null,
    			getResources().getString(R.string.T_Verifing_short));
   		new Thread(completedVerifyRunnable).start();	   	
	}

    private Runnable completedVerifyRunnable = new Runnable() {
		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();  
			//设置连接超时时间
			HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
			HttpClient httpClient = new DefaultHttpClient(httpParams);
			//取得动态注册的Url地址
			String urlString;
			clientId = PushManager.getInstance().getClientid(VerifyPassWordActivity.this);
			if (fromFlag.equals("SignUp")) {
				urlString = ConfigProperties.getVerifySignUpUrl();
			}else{
				urlString =ConfigProperties.resetPasswordUrl();			
			}
			HttpPost httpPost = new HttpPost(
					urlString);
			List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
			paramsList.add(new BasicNameValuePair("phoneNo", customerPhoneNumber));
			paramsList.add(new BasicNameValuePair("dynamicCode", dynamicCode));			
			//如果是注册，则要发送个推的clientId
			if (fromFlag.equals("SignUp")) {
				paramsList.add(new BasicNameValuePair("cstPassword", cstPassword));
				paramsList.add(new BasicNameValuePair("clientId", clientId));	
			}else{
				paramsList.add(new BasicNameValuePair("newPassword", cstPassword));
			}
			UrlEncodedFormEntity entity;
			Message msg = new Message();
			Bundle data = new Bundle();
			try {
				entity = new UrlEncodedFormEntity(paramsList, "utf-8");			
				httpPost.setEntity(entity);
				HttpResponse httpResponse = httpClient.execute(httpPost);
				//验证Http响应状态码				
				if (httpResponse.getStatusLine().getStatusCode() == 200) {					
					//获取响应实体
					HttpEntity httpEntity = httpResponse.getEntity();
					//获取服务器返回的信息，转换为UTF-8编码的字符串
					if (httpEntity != null) {
						String res = EntityUtils.toString(httpEntity, Charset
								.forName("UTF-8").toString());
						data.putString("value", res);
						httpEntity.consumeContent();
					}
				}else if(httpResponse.getStatusLine().getStatusCode() == 500){
					data.putString("Error", getResources().getString(R.string.T_Servicer_Error_500));					
				}
			} catch (UnsupportedEncodingException e) {
				data.putString("Error", getResources().getString(R.string.T_Verify_Failure));
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				data.putString("Error", getResources().getString(R.string.T_Verify_Failure));
					e.printStackTrace();
			} catch (IOException e) {
				data.putString("Error", getResources().getString(R.string.T_Verify_Failure));
					e.printStackTrace();			
			}finally {
				//发送message。关闭连接
				msg.setData(data);
				resultVerifyhandler.sendMessage(msg);
				httpClient.getConnectionManager().shutdown();
			} 
			
		}
	};
    /**
     * 处理服务器返回结果
     * 成功--登录/重新登录
     * 失败--提示原因
     */
	private Handler resultVerifyhandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			//关闭对话框
			pd.dismiss();

			Bundle data = msg.getData();
			String error = data.getString("Error");			
			if (error != null && !error.isEmpty()) {
				showToast(error);
				return;
			}
			//取出并处理JSON字符串
			String val = data.getString("value");
			try {
				JSONObject result = new JSONObject(val);	
				//登录响应状态
				boolean isSuccess = result.getBoolean("success");
				if (isSuccess) {
					Log.d("成功", "true");
					if (fromFlag.equals("SignUp")) {
						showToast(getResources().getString(R.string.T_regist_Success));
						MyApplication.getInstance().setCstToken(result.getString("cstToken"));
						MyApplication.getInstance().setUserId(customerPhoneNumber);
						setResult(RESULT_OK);
					}else if(fromFlag.equals("ForgotPassWord")){
						showToast(getResources().getString(R.string.T_ResetPassword_Success));					
						setResult(RESULT_OK);
						
					}
					finish();
//					Intent intent = new Intent();
//					intent.setClass(VerifyPassWordActivity.this, LoginActivity.class);
//					startActivity(intent);
				} else {
					String message = result.getString("msg");
					showToast(message);
				}
			} catch(Exception e){
				showToast(getResources().getString(R.string.T_Verify_Failure));
			}
		}
	};
	/**
     * 设置倒计时
     * 
     *
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }
        @Override
        public void onFinish() {//计时完毕时触发
            countDown.setText(R.string.Resend_AuthCode);
            countDown.setEnabled(true);
        }
        @Override
        public void onTick(long millisUntilFinished){//计时过程显示
            countDown.setEnabled(false);
            countDown.setText(getResources().getString(R.string.CountDown) 
            		+ "（" + millisUntilFinished / 1000 + "）");
        }
    }
    private void initView() {       
        showPhoneNumber = (TextView) findViewById(R.id.tv_show_phone_number);
        authCode = (EditText) findViewById(R.id.edit_authcode);
        resetAuthCode = (Button) findViewById(R.id.btn_reset_authcode);
        countDown = (Button) findViewById(R.id.tv_countdown);
        customerPassword = (EditText) findViewById(R.id.edit_password);
        resetPassword = (Button) findViewById(R.id.btn_reset_password);
        submitButton = (Button) findViewById(R.id.btn_submit);
        passwordVisible = (Button) findViewById(R.id.btn_password_visible);
    }
    private void initHeader(){
    	//头部半透明
    	RelativeLayout rl_head = (RelativeLayout) this.findViewById(R.id.verify_signup);
    	rl_head.setBackgroundColor(Color.argb(60, 0, 0, 0));
    	//注册返回按钮事件
		Button backBtn = (Button) findViewById(R.id.ivBack);
		backBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View view) {				
				VerifyPassWordActivity.this.finish();
			}
		});
		//设置Title文字为注册
		TextView center = (TextView) findViewById(R.id.tvTitle);
		if (fromFlag.equals("SignUp")) {			
			center.setText(R.string.Sign_Up); 
		}else if (fromFlag.equals("ForgotPassWord")) {
			center.setText(R.string.Forgot_Password);
		}
		       	
	}
}
